package net.rlair.sbdemo.service;

import net.rlair.sbdemo.ContextUtils;
import net.rlair.sbdemo.dao.mybatis.bootmapper.UserMapper;
import net.rlair.sbdemo.entity.User;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TxNestedZhaozichen {


    @Resource
    private ContextUtils contextUtils;

    @Resource
    private UserMapper userMapper;

    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED)
    public int batchAddUsers() {
        int count = 0;
        TxNestedZhaozichen userService = contextUtils.getApplicationContext().getBean(TxNestedZhaozichen.class);
        final List<User> users = new ArrayList();
        users.add(userService.createUser(1));
        users.add(userService.createUser(2));
        for (User user : users) {
            try {
                count += userService.addUser(user);
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
        count += userMapper.addUser(createUser(3));
        return count;
    }

    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRES_NEW)
    public int addUser(final User user) {
        int count = userMapper.addUser(user);
        if (user.getId() == 3) {
            count = 1 / 0;
        }
        return count;
    }

    public User createUser(int id) {
        final User user = new User();
        user.setId(id);
        user.setCreated(new Date());
        user.setName("name" + id);
        user.setPassword("password " + id);
        user.setUpdated(new Date());
        return user;
    }

}
